<template>
  <div class="home">
    <div class="detailsTitle">
      <div class="detailsTitleLeft">
        <div class="leftTitle">{{ problemData.problemname }}</div>
        <div class="shenLue" v-if="!showMore">{{ problemData.textReplace }}</div>
        <div v-else>
          <div class="ql-snow ql-editor" v-html="problemData.content"></div>
        </div>
        <div class="showMore" @click="showMore = !showMore">{{ showMore ? "收起更多" : "展开更多" }}</div>
        <div class="leftButton">
          <el-button
            :class="[isProLikeStuta ? 'collectionBtn2' : 'collectionBtn']"
            @click="proLike"
          >{{ isProLikeStuta ? "已收藏" : "收藏本帖" }}</el-button>
          <el-button class="commentBtn" @click="answer">写回答</el-button>
        </div>
      </div>

      <div class="detailsTitleRight">
        <div class="collectionNum">
          <div class="title">回答数</div>
          <div class="num">{{ problemData.reply }}</div>
        </div>
        <div class="browseNum">
          <div class="title">浏览数</div>
          <div class="num">{{ problemData.reading }}</div>
        </div>
      </div>
    </div>

    <div class="content">
      <div class="left">
        <noMore v-if="answerData.length == 0"></noMore>

        <div class="more" @click="showMoreAnswer" v-if="isShowMoreAnswer">查看全部 {{ answerSize }} 个回答</div>

        <div class="leftContent" v-for="(item, index) in answerData" :key="index">
          <div class="caiNa" v-if="item.adopt == 1">
            <img src="../../../public/img/caiNa/已采纳.png" style="width:60px;height:60px" />
          </div>
          <div class="author">
            <div>
              <el-avatar size="large" :src="avatarURL + item.userid.head_portrait"></el-avatar>
            </div>
            <div class="authorInfo">
              <div class="name" @click="toOtherPerson(item.userid._id)">{{ item.userid.name }}</div>
              <div class="subtitle">{{ item.userid.autograph }}</div>
            </div>
          </div>

          <div class="ql-snow ql-editor" v-html="item.content"></div>

          <actionBar
            ref="actionBar"
            :articleData="item"
            :isLike="item.Like.isLike"
            :commentData="item.fistCom"
            :commentDataSize="item.showCom"
            :problemData="problemData"
            @giveALike="giveALike($event, index, item._id)"
            @articleLike="articleLike(index, item._id)"
            @comment="comment($event, index, item._id)"
            @comeBalckComment="comeBalckComment(arguments, index, item._id)"
            @getPraise="getPraise(arguments, index)"
            @delectFirComm="delectFirComm(arguments, index)"
            @delectSecComm="delectSecComm(arguments, index)"
            @moreComment="moreComment(index)"
            @overhead="overhead(index)"
            @articleAdopt="articleAdopt(index)"
          ></actionBar>
        </div>

        <div class="more2" @click="showMoreAnswer" v-if="isShowMoreAnswer">查看全部 {{ answerSize }} 个回答</div>
      </div>

      <div class="right">
        <userRight
          :authorData="(answerData[0] && answerData[0].userid) || {}"
          :articleId="problemData._id"
        ></userRight>
      </div>
    </div>
  </div>
</template>

<script>
import userRight from "./components/right";
import actionBar from "./components/actionBar";
import { get_problem, put_problem } from "@/api/problem";
import { GetAnswers, put_answer } from "@/api/answer";
import { defaultAvatarURL } from "../../utils/global";
import { post_like, delete_like, get_like } from "../../api/like";
import { post_comment, put_comment, delectComment } from "../../api/comment";
import { post_comfabulous, delete_comfabulous } from "../../api/comfabulous";
import { get_history, post_history } from "../../api/history";
import { sendMessage } from "../../api/Chat.js";

import noMore from "@/components/noMore";
export default {
  name: "HelpDetails",
  data() {
    return {
      avatarURL: defaultAvatarURL,
      showMore: false,
      problemData: {}, //问题
      answerData: [], //回答
      answerSize: 0, //回答数量
      isShowMoreAnswer: true, //显示全部回答
      answer_id: {}, //收藏跳转文章定位
      isProLikeStuta: false
    };
  },
  components: {
    userRight,
    actionBar,
    noMore
  },
  watch: {
    async $route() {
      //监听路由是否变化
      if (this.$route.query.problem_id) {
        let problemData = await get_problem({
          query: {
            _id: this.$route.query.problem_id
          },
          populate: JSON.stringify([
            {
              path: "userid"
            }
          ])
        });
        console.log("problemData", problemData.data[0]);
        this.problemData = problemData.data[0];
        this.isProLike();
        this.queryHistory();
        this.getAnswerData(
          {},
          {
            limit: 1,
            sort: { adopt: -1, topping: -1, reply: -1 },
            count: true
          }
        );
        this.isShowMoreAnswer = true;
        this.showMore = false;
      }
    }
  },
  async created() {
    if (!this.$route.query.problem_id) {
      this.$router.push({
        path: "/help"
      });
      return;
    }
    if (this.$route.query.answer_id) {
      this.answer_id._id = this.$route.query.answer_id;
    }
    let problemData = await get_problem({
      query: {
        _id: this.$route.query.problem_id
      },
      populate: JSON.stringify([
        {
          path: "userid"
        }
      ])
    });
    console.log("problemData", problemData.data[0]);
    this.problemData = problemData.data[0];
    this.isProLike();
    this.queryHistory();
    this.getAnswerData(
      {},
      {
        limit: 1,
        sort: { adopt: -1, topping: -1, reply: -1 },
        count: true
      }
    );
  },
  methods: {
    //其他用户主页
    toOtherPerson(val) {
      if (val == this.$store.getters.userInfo._id) {
        this.$router.push({
          path: "/personalCenter",
          query: {}
        });
        return;
      }
      this.$router.push({
        path: "/otherPerson",
        query: {
          user_id: val
        }
      });
    },
    //判断浏览历史
    async queryHistory() {
      let queryData = await get_history({
        query: {
          articleid: this.problemData._id,
          userid: this.$store.getters.userInfo._id
        }
      });
      if (queryData.data.length == 0) {
        await put_problem({
          query: {
            _id: this.problemData._id
          },
          update: {
            $inc: {
              reading: 1
            }
          }
        });

        await post_history({
          articleid: this.problemData._id,
          artictype: this.problemData.problemtype,
          userid: this.$store.getters.userInfo._id,
          history_time: new Date()
        });
        // this.$message({
        //   showClose: true,
        //   message: "首次阅读获得积分",
        //   type: "success"
        // });
      }
      this.$finish_taskdata(1, this.$store.getters.userInfo._id);
    },
    async getAnswerData(query, condition) {
      let anData = await GetAnswers({
        query: {
          problem_id: this.problemData._id,
          audit: true,
          ...this.answer_id,
          ...query
        },
        ...condition,
        sort: { adopt: -1, topping: -1, reply: -1 },
        likeUserId: this.$store.getters.userInfo._id
      });
      this.answerData = anData.data;
      console.log("互帮互助anData", anData.countnum);

      if (anData.countnum || anData.countnum == 0) {
        this.answerSize = anData.countnum;
      }
      if (this.answerData.length == 0) {
        this.isShowMoreAnswer = false;
      }
    },
    async showMoreAnswer() {
      let anData = await GetAnswers({
        query: {
          problem_id: this.problemData._id,
          audit: true,
          _id: {
            $ne: this.answerData[0]._id
          }
        },
        sort: { adopt: -1, topping: -1, reply: -1 },
        likeUserId: this.$store.getters.userInfo._id
      });
      this.answerData = this.answerData.concat(anData.data);
      this.isShowMoreAnswer = false;
    },
    answer() {
      if (this.problemData.userid._id == this.$store.getters.userInfo._id) {
        return this.$message({
          message: "不能回答自己的问题",
          type: "warning"
        });
      }
      this.$router.push({
        path: "/writeAnswer",
        query: {
          problem_id: this.problemData._id
        }
      });
    },
    //点赞
    async giveALike(isActive, dataIndex, answerid) {
      console.log("点赞事件", isActive);

      if (isActive) {
        // return;
        //取消点赞
        var index = this.answerData[dataIndex].praise.indexOf(
          this.$store.getters.userInfo._id
        );
        if (index > -1) {
          this.answerData[dataIndex].praise.splice(index, 1);
        }
        await put_answer({
          query: {
            _id: answerid
          },
          update: {
            $pull: {
              praise: this.$store.getters.userInfo._id
            },
            $inc: {
              praiseSize: -1
            }
          }
        });
      } else {
        this.answerData[dataIndex].praise.push(
          this.$store.getters.userInfo._id
        );
        await put_answer({
          query: {
            _id: answerid
          },
          update: {
            $addToSet: {
              praise: this.$store.getters.userInfo._id
            },
            $inc: {
              praiseSize: 1
            }
          }
        });
        this.$finish_taskdata(9, this.$store.getters.userInfo._id);
      }
    },
    //初始化收藏问题
    async isProLike() {
      let like = await get_like({
        query: {
          problem_id: this.problemData._id,
          userid: this.$store.getters.userInfo._id
        }
      });
      console.log("like", like);
      if (like.data.length == 0) {
        this.isProLikeStuta = false;
      } else {
        this.isProLikeStuta = true;
      }
    },
    //收藏问题
    async proLike() {
      if (this.isProLikeStuta) {
        await delete_like({
          query: {
            problem_id: this.problemData._id,
            userid: this.$store.getters.userInfo._id
          }
        });
        this.isProLikeStuta = false;
      } else {
        await post_like({
          problem_id: this.problemData._id,
          artictype: this.problemData.problemtype,
          userid: this.$store.getters.userInfo._id,
          like_time: new Date()
          // answer_id: answerid
        });
        this.isProLikeStuta = true;
      }
    },
    //文章收藏
    async articleLike(dataIndex, answerid) {
      if (this.answerData[dataIndex].Like.isLike) {
        await delete_like({
          query: {
            _id: this.answerData[dataIndex].Like._id
          }
        });
        this.answerData[dataIndex].Like.isLike = false;
      } else {
        let postLike = await post_like({
          // problem_id: this.problemData._id,
          artictype: this.problemData.problemtype,
          userid: this.$store.getters.userInfo._id,
          like_time: new Date(),
          answer_id: answerid
        });
        console.log("postLike", postLike);
        this.answerData[dataIndex].Like.isLike = true;
        this.answerData[dataIndex].Like._id = postLike.data._id;
        this.$finish_taskdata(4, this.$store.getters.userInfo._id);
      }
    },
    //发送文章评论
    async comment(commentTetx, dataIndex, answerid) {
      if (commentTetx == "") return;
      await post_comment({
        userid: this.$store.getters.userInfo._id,
        articleid: this.answerData[dataIndex]._id,
        aeticletype: this.problemData.problemtype,
        content: commentTetx,
        release_time: new Date()
      });
      await put_answer({
        query: {
          _id: answerid
        },
        update: {
          $inc: {
            reply: 1
          }
        }
      });
      this.answerData[dataIndex].fistCom.push({
        userid: this.$store.getters.userInfo,
        articleid: this.answerData[dataIndex]._id,
        aeticletype: this.problemData.problemtype,
        content: commentTetx,
        release_time: new Date(),
        praise: []
      });
      this.$refs.actionBar[dataIndex].commentTetx = "";
      this.$message({
        showClose: true,
        message: "消息已发送",
        type: "success"
      });
      // console.log("评论：", commentTetx);
      this.$finish_taskdata(3, this.$store.getters.userInfo._id);
    },
    //二级评论
    async comeBalckComment(argument, dataIndex) {
      // console.log(commentid, replyid, index, comeBalckCommentTetx);
      if (argument[3] == "") return;
      await post_comfabulous({
        userid: this.$store.getters.userInfo._id, //用户id
        commentid: argument[0], //评论id
        replyid: argument[1]._id, //回复的人
        content: argument[3], //评论内容
        release_time: new Date() //发布时间
      });
      this.answerData[dataIndex].fistCom[argument[2]].secondComment.push({
        userid: this.$store.getters.userInfo, //用户id
        commentid: argument[0], //评论id
        replyid: argument[1], //回复的人
        content: argument[3], //评论内容
        release_time: new Date() //发布时间
      });
      this.$refs.actionBar[dataIndex].comeBalckCommentTetx = "";
      this.$refs.actionBar[dataIndex].comeBalckInput = "";
      this.$message({
        showClose: true,
        message: "消息已发送",
        type: "success"
      });
    },
    //评论点赞
    async getPraise(argument, dataIndex) {
      //isPra, comId, index
      if (argument[0]) {
        var arrIndex = this.answerData[dataIndex].fistCom[
          argument[2]
        ].praise.indexOf(this.$store.getters.userInfo._id);
        this.answerData[dataIndex].fistCom[argument[2]].praise.splice(
          arrIndex,
          1
        );
        await put_comment({
          query: {
            _id: argument[1]
          },
          update: {
            $pull: {
              praise: this.$store.getters.userInfo._id
            }
          }
        });
      } else {
        this.answerData[dataIndex].fistCom[argument[2]].praise.push(
          this.$store.getters.userInfo._id
        );
        await put_comment({
          query: {
            _id: argument[1]
          },
          update: {
            $addToSet: {
              praise: this.$store.getters.userInfo._id
            }
          }
        });
      }
    },
    //删除一级评论
    async delectFirComm(argument, dataIndex) {
      //item, index
      this.$confirm("此操作将永久删除该评论, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await delectComment({
          query: {
            _id: argument[0]
          }
        });
        this.answerData[dataIndex].fistCom.splice(argument[1], 1);
        this.$message({
          showClose: true,
          type: "success",
          message: "删除成功!"
        });
      });
    },
    //删除二级评论
    async delectSecComm(argument, dataIndex) {
      //item, index, index2
      this.$confirm("此操作将永久删除该评论, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await delete_comfabulous({
          query: {
            _id: argument[0]
          }
        });
        this.answerData[dataIndex].fistCom[argument[1]].secondComment.splice(
          argument[2],
          1
        );
        this.$message({
          showClose: true,
          type: "success",
          message: "删除成功!"
        });
      });
    },
    moreComment(dataIndex) {
      this.answerData[dataIndex].showCom =
        this.answerData[dataIndex].showCom + 5;
    },
    //置顶
    async overhead(dataIndex) {
      if (this.answerData[dataIndex].topping == 0) {
        this.answerData[dataIndex].topping = 1;
      } else {
        this.answerData[dataIndex].topping = 0;
      }
      await put_answer({
        query: {
          _id: this.answerData[dataIndex]._id
        },
        update: {
          $set: {
            topping: this.answerData[dataIndex].topping
          }
        }
      });
    },
    //采纳
    async articleAdopt(dataIndex) {
      if (this.answerData[dataIndex].adopt == 0 && this.problemData.adopt) {
        return this.$alert("您已经采纳回答", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
      if (this.answerData[dataIndex].adopt == 0) {
        // console.log("采纳文章信息", this.answerData[dataIndex]);
        this.$confirm("采纳此回答后不可更改, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            this.answerData[dataIndex].adopt = 1;
            this.problemData.adopt = this.answerData[dataIndex]._id;
            await put_problem({
              query: {
                _id: this.problemData._id
              },
              update: {
                $set: {
                  adopt: this.answerData[dataIndex]._id
                }
              }
            });

            await put_answer({
              query: {
                _id: this.answerData[dataIndex]._id
              },
              update: {
                $set: {
                  adopt: this.answerData[dataIndex].adopt
                }
              }
            });
            this.$finish_taskdata(6, this.answerData[dataIndex].userid._id);
            // 给问题的回答的人发私信
            var data = {
              user_id: this.$store.getters.userInfo._id,
              friend_id: this.answerData[dataIndex].userid._id,
              liaoTianContent: "谢谢您的回复，为我答疑解惑~",
              chat_content_time: new Date()
            };
            console.log(data);
            sendMessage(data).then(res => {
              console.log(res);
            });
            this.$message({
              type: "success",
              message: "已采纳该回答!"
            });
          })
          .catch(() => {});
      }

      // else {
      //   this.answerData[dataIndex].adopt = 0;
      //   this.problemData.adopt = "";
      //   await put_problem({
      //     query: {
      //       _id: this.problemData._id
      //     },
      //     update: {
      //       $unset: {
      //         adopt: ""
      //       }
      //     }
      //   });
      //   await put_answer({
      //     query: {
      //       _id: this.answerData[dataIndex]._id
      //     },
      //     update: {
      //       $set: {
      //         adopt: this.answerData[dataIndex].adopt
      //       }
      //     }
      //   });
      // }
    }
  }
};
</script>

<style lang="scss" scoped>
.home {
  // padding: 10px 10px;
  width: 100%;
  // margin-bottom: 300px;
}
.detailsTitle {
  width: 100%;
  background: #fff;
  margin-top: -10px;
  min-height: 130px;
  border-radius: 10px;
  padding: 30px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;

  .detailsTitleLeft {
    width: 70%;
    .shenLue {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2; /* 可以显示的行数，超出部分用...表示*/
      -webkit-box-orient: vertical;
    }
    .showMore {
      float: right;
      color: #1d2f70;
      cursor: pointer;
      margin-top: 10px;
      font-weight: 600;
      font-size: 14px;
    }
    .leftTitle {
      font-size: 23px;
      font-weight: 600;
      color: #333;
    }
    .leftButton {
      margin-top: 20px;
      .collectionBtn {
        background: #1d2f70;
        border: #1d2f70;
        color: #fff;
        &:hover {
          background: rgb(53, 89, 180);
        }
      }
      .collectionBtn2 {
        background: #616164;
        border: #1d2f70;
        color: #fff;
        &:hover {
          background: rgb(53, 89, 180);
        }
      }
      .commentBtn {
        background: #fff;
        border: #1d2f70 1px solid !important;
        color: #1d2f70 !important;
        margin-left: 20px;
        &:hover {
          background: rgb(237, 238, 240);
        }
      }
    }
  }
  .detailsTitleRight {
    // width: 25%;
    display: flex;
    color: #6c6c6c;
    font-size: 17px;
    font-weight: 530;
    margin-right: 20px;
    .collectionNum {
      text-align: center;
      .num {
        color: #3257b5;
        font-size: 24px;
        font-weight: 600;
        margin-top: 8px;
      }
    }
    .browseNum {
      text-align: center;
      margin-left: 20px;
      .num {
        color: #3257b5;
        font-size: 24px;
        font-weight: 600;
        margin-top: 8px;
      }
    }
  }
}
.content {
  display: flex;
  width: 100%;
  justify-content: space-between;
  margin-top: 20px;
  .left {
    width: 74%;
    .more {
      background: #fff;
      width: 100%;
      border-radius: 10px;
      padding: 10px;
      margin-bottom: 10px;
      box-sizing: border-box;
      text-align: center;
      color: #6c6c6c;
      font-size: 16px;
      cursor: pointer;
    }
    .more2 {
      background: #fff;
      width: 100%;
      border-radius: 10px;
      padding: 10px;
      margin-top: 10px;
      box-sizing: border-box;
      text-align: center;
      color: #6c6c6c;
      font-size: 16px;
      cursor: pointer;
    }
    .leftContent {
      background: #fff;
      width: 100%;
      box-sizing: border-box;
      padding: 20px;
      border-radius: 10px;
      margin-bottom: 10px;
      position: relative;
      .caiNa {
        position: absolute;
        right: 20px;
        top: 20px;
      }
      .author {
        display: flex;
        &:hover {
          cursor: pointer;
        }
        .authorInfo {
          margin-left: 10px;
          .name {
            font-size: 15px;
            font-weight: 600;
          }
          .subtitle {
            font-size: 14px;
            color: #6c6c6c;
          }
        }
      }
    }
  }

  .right {
    width: 25%;
  }
}
</style>
